package com.andro.inje.chansung.bus;

import java.util.List;

import com.andro.inje.chansung.ConstantName;
import com.andro.inje.chansung.DB;
import com.andro.inje.chansung.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

public class BusTimeActivity extends Activity implements OnItemClickListener {
	private BusTimeHandler handler;
	private GridView gridView;
	private ProgressDialog pd;
	private Activity activity;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bus_time_check_layout);
		
		SQLiteDatabase db = openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
		DB.removeBusTables(db);
		DB.createBusTables(db);
		db.close();
		
		handler = new BusTimeHandler();
		
		gridView = (GridView)findViewById(R.id.bus_time_check_table);
		gridView.setOnItemClickListener(this);
		
		BusUpdateThread thread = new BusUpdateThread(this, handler);
		pd = ProgressDialog.show(this, "로딩중", "버스 정보 로딩..");
		thread.start();
		
		activity = this;
	}

	public class BusTimeHandler extends Handler {
		public void handleMessage(Message msg) {
			SQLiteDatabase db = openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_READABLE, null);
			List<Bus> buses = DB.getAllBusLists(db);
			db.close();
			
			for( Bus bus : buses ) {
				Log.d("name", bus.getDestination());
			}
			
			gridView.setAdapter(new BusBasicAdapter(activity, buses));
			pd.dismiss();
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		SQLiteDatabase db = openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_READABLE, null);
		List<Bus> buses = DB.getAllBusLists(db);
		db.close();
		
		Intent intent = new Intent(this, BusDetailActivity.class);
		intent.putExtra("name", buses.get(position).getDestination());
		startActivity(intent);
	}
}
